package edu.uwosh.cs342.placestobe;

import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class MakeMeeting extends Activity implements OnClickListener{

	ArrayAdapter<CharSequence> friendAdapter;
	protected ArrayList<CharSequence> selectedFriends = new ArrayList<CharSequence>();
	String[] listOfFriends;
	String[] listOfLocations;
	String[] meetingFriends;
	String locationSelected = "";
	
	EditText friendsInvitedEditText;
	DatePicker datePicker;
	TimePicker timePicker;
	Double[] lat;
	Spinner locSelection;
	Double[]lng;
	EditText Description;
	
	ArrayAdapter<CharSequence> Adapterloc;
	//private List<CharSequence> featuresList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newmeeting);
		
		//  get intent to show spinners
		Intent i = getIntent();
			
		//  friend spinner
		listOfFriends = i.getStringArrayExtra("listOfFriends");
		
		locationSelected = i.getStringExtra("locationName");
		
		lat = new Double[(MainActivity.size)];
		lng = new Double[(MainActivity.size)];
		String[] places = new String[(MainActivity.size)];
		lat = MainActivity.latA;
		lng = MainActivity.lngA;
		places =  MainActivity.placesA;
		System.out.println(places.length);
		Adapterloc = new ArrayAdapter<CharSequence>(this,
		  android.R.layout.simple_spinner_item, places);
		Adapterloc.setDropDownViewResource(
		  android.R.layout.simple_spinner_dropdown_item);
		locSelection = ((Spinner) MakeMeeting.this.findViewById(R.id.locationSpinner));
		locSelection.setAdapter(Adapterloc);
		
		int setLocationIndex = 0;
		if (!locationSelected.equals("")){
			//  Find location from places array
			for(int j = 0; j < places.length; j++){
				if (places[j].equals(locationSelected)){
					setLocationIndex = j;
				}
			}	
		}
		
		locSelection.setSelection(setLocationIndex);
			
		//  instantiating DatePicker
		datePicker = (DatePicker) findViewById(R.id.datePicker1); 
		
		//  instantiating TimePicker
		timePicker = (TimePicker) findViewById(R.id.timePicker1);
		
		//  handles when the meeting is made
		Button submit = (Button) findViewById(R.id.makeMeetingButton);
		submit.setOnClickListener(this);
		
		//  
		Button selectFriendsButton = (Button) findViewById(R.id.selectFriendsButton);
		selectFriendsButton.setOnClickListener(this);
		
		friendsInvitedEditText =  (EditText) findViewById(R.id.friendEditText);

	}
	
	

	public void onClick(View view) {
		switch(view.getId()) {
	      case R.id.makeMeetingButton:
				//  getting user's entered data
				ArrayList<CharSequence> friendsMeeting = selectedFriends;
				int monthMeeting = datePicker.getMonth();
				int dayMeeting = datePicker.getDayOfMonth();
				int yearMeeting = datePicker.getYear();
				int hourMeeting = timePicker.getCurrentHour();
				int minMeeting =  timePicker.getCurrentMinute();
				String description = "";
				String location = (String) locSelection.getSelectedItem();
				int locloc = (int) locSelection.getSelectedItemId();
				 Description =(EditText) findViewById(R.id.editText1);
				 description = Description.getText().toString();
				 description = description.replace(" ", "%20");
				//  **** location not done yet ****  
				System.out.println(location + " lat: "+lat[locloc] +" long "+ lng[locloc]);
				String res ="";
				String meetingID = "";
				String userID = MainActivity.userID;
				try {  
					System.out.println(Description);
					res= CustomHttpClient.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/createEvent.php?description="+description+"&lat="+lat[locloc]+"&long="+lng[locloc]+"&date="+monthMeeting + "-"+ dayMeeting + "-" + yearMeeting + "%20"+ hourMeeting +":"+minMeeting); 
					meetingID=res.toString().trim();    
				} catch (Exception e) { Toast.makeText(getApplicationContext(),
						"ERROR! "+ e.toString(),
						Toast.LENGTH_LONG).show(); System.out.println(e.toString());}
				try {  
					for(int i = 0; i<friendsMeeting.size(); i++){
						System.out.println(friendsMeeting.get(i));
						res= CustomHttpClient.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/inviteUser.php?meetID="+meetingID+"&userID="+friendsMeeting.get(i)); 
						res=res.toString().trim();
						if (!res.equalsIgnoreCase("1")){
							Toast.makeText(getApplicationContext(),
									"Error Sending request to friends",
									Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(getApplicationContext(),
									"Meeting Created!",
									Toast.LENGTH_LONG).show();
						}
					}
					
					res= CustomHttpClient.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/inviteUser.php?meetID="+meetingID+"&userID="+userID); 
					res=res.toString().trim();
					if (!res.equalsIgnoreCase("1")){
						Toast.makeText(getApplicationContext(),
								"Error Sending request to friends",
								Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) { Toast.makeText(getApplicationContext(),
						"ERROR! "+ e.toString(),
						Toast.LENGTH_LONG).show();
						System.out.println(e.toString());}
				
				finish();
	        break;
	        
	      case R.id.selectFriendsButton:
	    	  showFriendsListSelectionDialog();
	    	break;
	    	
	      default:
	        break;
	    }
		
	} 
	
	protected void showFriendsListSelectionDialog() {
		  boolean[] checkedFriends = new boolean[listOfFriends.length];
		  int count = listOfFriends.length;
		 
		  for(int i = 0; i < count; i++)
		    checkedFriends[i] = selectedFriends.contains(listOfFriends[i]);
		 
		  DialogInterface.OnMultiChoiceClickListener friendsDialogListener = new DialogInterface.OnMultiChoiceClickListener() {
		   public void onClick(DialogInterface dialog, int which, boolean isChecked) {
		      if(isChecked)
		        selectedFriends.add(listOfFriends[which]);
		      else
		        selectedFriends.remove(listOfFriends[which]);
		 
		      onChangeSelectedFriends();
		    }
		   };
		 
		  AlertDialog.Builder builder = new AlertDialog.Builder(this);
		  builder.setTitle("Select Friends");
		  builder.setMultiChoiceItems(listOfFriends, checkedFriends, friendsDialogListener);
		  builder.setPositiveButton("Select Friends", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				//  **********  web service to accept the meeting request  ********
				
			}
		});
		 
		  AlertDialog dialog = builder.create();
		  dialog.show();
	}

	protected void onChangeSelectedFriends() {
		  StringBuilder stringBuilder = new StringBuilder();
		 
		  for(CharSequence friend : selectedFriends)
		    stringBuilder.append(friend + ",");
		 
		  friendsInvitedEditText.setText(stringBuilder.toString());
		}
	
}
